package logic

import (
	"api/pkg"
	"context"
	"net/http"
	"path/filepath"
	"time"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadImagesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadImagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadImagesLogic {
	return &UploadImagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadImagesLogic) UploadImages(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, header, err := req.FormFile("images")
	if err != nil {
		return &types.Response{
			Code:    500,
			Message: "获取图片信息失败",
			Data:    nil,
		}, nil
	}
	ext := filepath.Ext(header.Filename)
	if ext != ".png" && ext != ".jpg" {
		return &types.Response{Code: 500, Message: "图片格式只能是.png或者.jpg", Data: nil}, nil
	}
	if header.Size > 2*1024*1024 {
		return &types.Response{Code: 500, Message: "图片大小不能超过2MD", Data: nil}, nil
	}
	fileName := time.Now().Format("20060102150405") + ext

	upload, err := pkg.UploadImages(file, fileName)
	if err != nil {
		return &types.Response{Code: 500, Message: "上传图片失败", Data: nil}, nil
	}
	return &types.Response{
		Code:    200,
		Message: "上传图片成功",
		Data: map[string]interface{}{
			"Upload": upload,
		},
	}, nil
}
